import 'dart:io';

import 'package:dio/dio.dart';
import 'package:fsharing/core/models/protocol.dart';
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DioInterceptor extends InterceptorsWrapper {
  static final _ignores = ['/s/oauth/token', '/s/me', '/api/logistics'];

  final AppStoreModel appStoreModel;
  final AppLoginModel appLoginModel;

  DioInterceptor(this.appStoreModel, this.appLoginModel);

  @override
  Future onRequest(RequestOptions options) async {
    options.headers['bindingStoreId'] = appStoreModel.bindingStoreId;
    options.headers['currentStoreId'] = appStoreModel.currentStoreId;
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String accessToken = sharedPreferences.getString('accessToken');
    if (accessToken != null) {
      options.headers['Authorization'] = 'Bearer $accessToken';
    }
    return options;
  }

  @override
  Future onError(DioError err) async {
    if (err.response?.statusCode == 401) {
      appLoginModel.isLogin = false;
      return '登录已失效，请重新登录';
    }
    if (err.error is SocketException) {
      return '服务器升级中，请稍后...';
    }
    return err.message;
  }

  @override
  Future onResponse(Response response) async {
    if (_ignores.contains(response.request.path)) {
      return response;
    }
    var protocol = Protocol.fromJson(response.data);
    if (protocol.code == 0) {
      response.data = protocol.data;
      return response;
    } else {
      throw DioError(response: response, error: protocol.message ?? '未知信息');
    }
  }
}
